var page=1;
var size=1000;
var base_url = "http://glitfc.leanapp.cn";
var url = window.location.href.split("/");
var bk_id = url[url.length - 1];
$(document).ready(function () {
    var url = base_url+"/book/chapter_list/" + bk_id + "?page=" + page + "&size=" + size;
    var method = "GET";
//    HttpReq(method, url);
    var box_hd = document.getElementsByClassName('box-hd')[0];
    var h3 = box_hd.getElementsByTagName('h3');
    var box_content = document.getElementsByClassName('box-content')[0];
    var chapterlist = document.getElementsByClassName('chapterlist-main')[0];
    var footer = document.getElementsByClassName("footer")[0];
    h3[0].onclick = function () {
        console.log('作品介绍');
        box_content.setAttribute("style", "display:block;");
        chapterlist.setAttribute("style", "display:none;");
        h3[0].className = ('active');
        h3[1].className = ('');
        footer.setAttribute("style", "display:block;");
    };
    h3[1].onclick = function () {
        console.log('作品目录');
        chapterlist.setAttribute("style", "display:block;");
        box_content.setAttribute("style", "display:none;");
        h3[1].className = ('active chapterlisttab');
        h3[0].className = ('');
        // footer.setAttribute("style", "display:none;");
        h3[1].className = ('active chapterlisttab');
        h3[0].className = ('');
    };
    var fav = document.getElementsByClassName("fav")[0];
    var user_id;
    var fav_id;
     $.getJSON(base_url+ "/user/get_user", {
                 //参数
             }, function (json) {
                 var code = json.code;
                 if (code == 200){
                     user_id = json.data.objectId;
                     if (user_id != null){
                           user_id = json.data.objectId;
                           $.getJSON(base_url+ "/book_fav/has/fav?book_id=" + bk_id + "&user_id=" + user_id, {
                             }, function (json) {
                                 var code = json.code;
                                 if (code == 200){
                                     var status = json.status;
                                     if(status === 1){
                                        fav.innerText = "移除书架";
                                        fav_id = json.fav_id;
                                        fav.setAttribute("value",fav_id);
                                     }
                                 }
             });
                           }
                     }
                 });


function iframelogin(){
               layui.use('layer', function(){
                  var layer = layui.layer;
                  layer.open({
                  skin: 'demo-class',
                  scrollbar:false,
                  area:['452px','402px'],
                  type: 2,
                  content: [local_url + '/static/login.html', 'no'] //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
                    });
                    });
           }
layui.use('flow', function(){
		  var $ = layui.jquery; //不用额外加载jQuery，flow模块本身是有依赖jQuery的，直接用即可。
		  var flow = layui.flow;
		  flow.load({
			elem: '.chapterlist' //指定列表容器
			,done: function(page, next){ //到达临界点（默认滚动触发），触发下一页
			  var lis = [];
			  //以jQuery的Ajax请求为例，请求下一页数据（注意：page是从2开始返回）
			  var url = base_url + "/book/chapter_list/" + bk_id + "?page=" + page + "&size=" + size;
			  $.get(url, function(res){
				//假设你的列表返回在data集合中
				layui.each(res.data.chapter, function(index, item){
				   var div = document.getElementsByClassName("chapterlist")[0];
                   var ul = div.getElementsByTagName("ul")[0];

				   var li = document.createElement("li");
                   var a = document.createElement("a");
                   li.appendChild(a);
                   ul.appendChild(li);
                   a.setAttribute("href", "/book_content/url?url=" + item.url);
                   a.innerHTML = item.zj;
				});

				//执行下一页渲染，第二参数为：满足“加载更多”的条件，即后面仍有分页
				//pages为Ajax返回的总页数，只有当前页小于总页数的情况下，才会继续出现加载更多
				next(lis.join(''), page < res.data.pages);
      });
    }
  });
});
});
    function onajaxtest(req) {
        var div = document.getElementsByClassName("chapterlist")[0];
        var ul = div.getElementsByTagName("ul")[0];
        var loading = div.getElementsByClassName("loading")[0];
        var loadingText = loading.getElementsByTagName("span")[0];

        if (req.data.chapter.length === 0){
            loadingText.innerText = "已加载全部数据";
        } else {
            for (var i = 0; i < req.data.chapter.length; i++) {

                var li = document.createElement("li");
                var a = document.createElement("a");
                li.appendChild(a);
                ul.appendChild(li);
                a.setAttribute("href", "/book_content/url?url=" + req.data.chapter[i].url);
                a.innerHTML = req.data.chapter[i].zj;
            }
        }
    }

    function HttpReq(method, url) {
        var xmlHttpReq = null;
        //IE浏览器使用ActiveX
        if (window.ActiveXObject) {
            xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
        }
        //其它浏览器使用window的子对象XMLHttpRequest
        else if (window.XMLHttpRequest) {
            xmlHttpReq = new XMLHttpRequest();
        }
        if (xmlHttpReq != null) {
            //设置请求（没有真正打开），true：表示异步
            xmlHttpReq.open(method, url, true);
            xmlHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xmlHttpReq.setRequestHeader("dataType", "json");

            if(method === "get"){
                xmlHttpReq.onreadystatechange = function () {
                if (xmlHttpReq.readyState === 4) {
                    var json = JSON.parse(xmlHttpReq.response);
                    onajaxtest(json);
                    return xmlHttpReq;
                }
            };
            xmlHttpReq.send(null);
            }else{
                  xmlHttpReq.onreadystatechange = function () {
//                console.log(xmlHttpReq.readyState);
                if (xmlHttpReq.readyState === 4) {
                    return xmlHttpReq;
                }}
                console.log(arguments[0]);
//                alert(arguments.length);
                if(arguments.length === 4){
                    xmlHttpReq.send("book_id=" + arguments[2] + "&user_id=" + arguments[3]);
                }else{
                    xmlHttpReq.send("fav_id=" + arguments[2]);
                }

            }

        }
    }


function fav(){
    var user_id;
    var fav = document.getElementsByClassName("fav")[0];
    var favId = document.getElementById("fav");
  $.getJSON(base_url+ "/user/get_user", {
                 //参数
             }, function (json) {
                 var code = json.code;
                 if (code == 200){
                     var Uname = json.data.username;
                     if (Uname != null){
                           user_id = json.data.objectId;
                           if(fav.innerText === "加入书架"){
                                HttpReq("post",base_url + "/book_fav/fav", bk_id, user_id);
                                fav.innerText = "移除书架";
                           }else{
                                console.log(favId.attributes.value.textContent);
//                                alert(favId.attributes.value.textContent);
                                HttpReq("post", base_url + "/book_fav/fav/del", favId.attributes.value.textContent);
                                fav.innerText = "加入书架";

                           }

//                           fav.setAttribute("onclick","");
                      }
             }else {
                   Uname = null;
                   fav.setAttribute("href", "login.html");
             }

                    });
             }
